package com.servicebuck.ui.model;

import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

@ManagedBean(name="usernew")
@SessionScoped
public class User {
	private String acsTkn;
	private String userName;
	private final String apiKey="165082900264810";
	private final String apiSecret="de35bc8cb0a4245d46aa9fa2658c8372";
	private static final String PROTECTED_RESOURCE_URL = "https://graph.facebook.com/me";
	public String getAccessToken() throws ParseException {
		FacesContext eq=FacesContext.getCurrentInstance();
		Map<String,String> map=eq.getExternalContext().getRequestParameterMap();
		String code=map.get("code");
		String ret=null;
		if(code!=null){
		    OAuthService service = new ServiceBuilder()
            .provider(FacebookApi.class)
            .apiKey(apiKey)
            .apiSecret(apiSecret)
            .callback("http://localhost:8080/ServiceBuck/pages/index.jsf")
            .build();
		    Verifier verifier = new Verifier(code);
		    Token accessToken = service.getAccessToken(null, verifier);
		    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
		    service.signRequest(accessToken, request);
		    Response response = request.send();
		    ret=response.getBody();
		    JSONParser parser=new JSONParser();
		    JSONObject obj2=(JSONObject)parser.parse(ret);
		    ret=(String)obj2.get("first_name");
		}
		return ret;
	}
	public void setAccessToken(String accessToken) {
		this.acsTkn = accessToken;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getRequestURL()
	{
	    Object request = FacesContext.getCurrentInstance().getExternalContext().getRequest();
	    if(request instanceof HttpServletRequest)
	    {
	            return ((HttpServletRequest) request).getRequestURL().toString();
	    }else
	    {
	        return "";
	    }
	}
	
	   public void processFragment(AjaxBehaviorEvent event) {
	       // this.accessToken=
	    }
	    public String getFragment() {
	        return acsTkn;
	    }

	    public void setFragment(String fragment) {
	        this.acsTkn = acsTkn;
}
}
